package com.qf.ability.message.handler;

import com.qf.ability.message.entity.Message;
import com.qf.ability.message.entity.Room;
import com.qf.ability.message.entity.UserSession;
import com.qf.ability.message.handler.base.BaseInChannelHandler;
import com.qf.ability.message.utils.RoomUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 直播方关闭消息
 * author Ken
 * create_time 2022/10/19
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class MasterCloseMsgInChannelHandler extends BaseInChannelHandler<Message> {

    @Override
    protected boolean isSupport(Message msg) {
        return msg.getId().equals("masterClose");
    }

    @Override
    protected void hander(ChannelHandlerContext ctx, Message msg) {
        Integer cid = msg.getCid();
        Room room = RoomUtils.get(cid);
        if (room.getMaster().getWebRtcEndpoint() != null) {
            room.getMaster().getWebRtcEndpoint().release();
        }

        //通知所有slave
        for (UserSession user : room.getSlaves().values()) {
            user.getWebRtcEndpoint().release();

            //通知所以客户端
            user.getChannel().writeAndFlush(new Message().setId("masterClose"));
        }
    }
}
